﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace monitor_server
{
    public delegate void form9enable(bool a);
    public partial class Form8 : Form
    {
        bool f9 = false;
        form8enable d;
        dev_add device, del_device;
        string[] oblast = new string[6];
        public Form8(form8enable sender1, dev_add sender2)
        {
            InitializeComponent();
            device = sender2;
            //Оставляем для измерителей параметры
            if (device.type == 1)
            {
                checkBox1.Enabled = true;
                checkBox1.Show();
                label6.Show();
                button4.Show();
            }
            //Для остальных прячем
            else
            {
                checkBox1.Enabled = false;
                checkBox1.Hide();
                label6.Hide();
                button4.Hide();
            }
            button4.Enabled = !device.take_params;
            checkBox1.Checked = device.take_params;
            del_device = new dev_add();
            d = sender1;
            oblast[0] = "Brest";
            oblast[1] = "Gomel";
            oblast[2] = "Grodno";
            oblast[3] = "Minsk";
            oblast[4] = "Mogilev";
            oblast[5] = "Vitebsk";
            
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;   //область
            comboBox2.DropDownStyle = ComboBoxStyle.DropDownList;   //группа
            comboBox3.DropDownStyle = ComboBoxStyle.DropDownList;   //зона выделения

            string[] cb1 = new string[] { "Брестская", "Витебская", "Гомельская", "Гродненская", "Минская", "Могилевская" };
            comboBox1.Items.AddRange(cb1);
            string[] cb2 = new string[] {"Анализаторы", "Измерители"};
            comboBox2.Items.AddRange(cb2);
            string[] cb3 = new string[] {"BLR01","BLR02","BLR03","BLR04","BLR05","BLR06","BLR07","BLR08","BLR09","BLR10","BLR11","BLR12"
                ,"BLR13","BLR14","BLR15","BLR16","BLR17","BLR18","BLR19","BLR20","BLR21","BLR22","BLR23","BLR24","BLR25", "BLR26"};
            /*string[] cb3 = new string[] {"ОЧС01","ОЧС02","ОЧС03","ОЧС04","ОЧС05","ОЧС06","ОЧС07","ОЧС08","ОЧС09","ОЧС10","ОЧС11","ОЧС12"
                ,"ОЧС13","ОЧС14","ОЧС15","ОЧС16","ОЧС17","ОЧС18","ОЧС19","ОЧС20","ОЧС21","ОЧС22","ОЧС23","ОЧС24","ОЧС25"};*/
            comboBox3.Items.AddRange(cb3);
            if (device.mod == true)
            {
                button1.Text = "Применить";
                del_device.name = textBox1.Text = device.name;
                textBox2.Text = device.ip;
                del_device.obl = device.obl;
                switch (device.obl)
                {
                    case "Brest":
                        comboBox1.SelectedIndex = 0;
                        break;
                    case "Vitebsk":
                        comboBox1.SelectedIndex = 1;
                        break;
                    case "Gomel":
                        comboBox1.SelectedIndex = 2;
                        break;
                    case "Grodno":
                        comboBox1.SelectedIndex = 3;
                        break;
                    case "Minsk":
                        comboBox1.SelectedIndex = 4;
                        break;
                    case "Mogilev":
                        comboBox1.SelectedIndex = 5;
                        break;
                }
                del_device.type = comboBox2.SelectedIndex = device.type;
                //del_device.dev = device.dev;
                int index = comboBox3.FindString(device.blr);
                comboBox3.SelectedIndex = index;
            }
            else
            {
                button1.Text = "Добавить";
                button3.Visible = false;
            }
        }

        void func9(bool param)
        {
            f9 = param;
            this.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            device.cancel = true;
            d(false, device);
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //device.mod = true;
            //Проверка на правильность заполнения параметров.
            bool err = false;
            bool errp = false;
            string error = "Не определены следующие параметры:";
            string errorp = "";
            if (comboBox1.SelectedItem == null)
            {
                err = true;
                error += "\r\nОбласть";
            }
            if (comboBox2.SelectedItem == null)
            {
                err = true;
                error += "\r\nГруппа";
            }
            if (comboBox3.SelectedItem == null)
            {
                if (comboBox2.SelectedIndex == 1)
                {
                    err = true;
                    error += "\r\nЗона частотного выделения";
                }
            }
            if (textBox1.Text == "")
            {
                err = true;
                error += "\r\nНазвание объекта";
            }
            IPAddress ip;
            if (!IPAddress.TryParse(textBox2.Text, out ip))
            {
                errp = true;
                errorp += "Введен некорректный IP-адрес";
            }
            if (err)
            {
                if (errp)
                    MessageBox.Show(error + "\r\n" + errorp);
                else
                    MessageBox.Show(error);
                return;
            }
            if (errp)
            {
                MessageBox.Show(errorp);
                return;
            }
            //Создание строки данных об объекте для сохранения в файл.
            device.blr = (string)comboBox3.SelectedItem;
            if (checkBox1.Checked)
                device.take_params = true;
            else
                device.take_params = false;
            /*if (comboBox2.SelectedIndex == 1)
                device.dev = true;
            else
                device.dev = false;*/
            device.type = comboBox2.SelectedIndex;
            device.ip = ip.ToString();
            switch ((string)comboBox1.SelectedItem)
            {
                case "Брестская":
                    device.obl = "Brest";
                    break;
                case "Витебская":
                    device.obl = "Vitebsk";
                    break;
                case "Гомельская":
                    device.obl = "Gomel";
                    break;
                case "Гродненская":
                    device.obl = "Grodno";
                    break;
                case "Минская":
                    device.obl = "Minsk";
                    break;
                case "Могилевская":
                    device.obl = "Mogilev";
                    break;
            }
            //device.name = textBox1.Text;
            device.name = "";
            for (int i = 0; i < textBox1.Text.Length; i++)
            {
                /*if (textBox1.Text[i] != ' ')
                    device.name += textBox1.Text[i];*/
                if (textBox1.Text[i] == ' ')
                {
                    if (i != textBox1.Text.Length - 1)
                    {
                        if (textBox1.Text[i + 1] == ' ')
                            continue;
                        device.name += textBox1.Text[i];
                    }                    
                }
                else
                    device.name += textBox1.Text[i];
            }
            if (device.mod)
            {
                //if (device.obl != device.prev_obl)
                //{
                int i = 0, type = -1, type1 = -1;
                string obl = "";
                string[] read_tree;
                string rtps = "";
                //dev = del_device.dev;
                type = del_device.type;
                rtps = del_device.name;
                obl = del_device.obl;
                read_tree = File.ReadAllLines(@"resources\maps\" + obl + ".ini", Encoding.GetEncoding("Windows-1251"));
                for (i = 0; i < 6; i++)
                {
                    if (oblast[i] != obl)
                    {
                        File.Copy(@"resources\maps\" + oblast[i] + ".ini", @"resources\maps\" + oblast[i] + "_t.ini");
                    }
                }

                //-----------------------------------Удаление Объекта---------------------------------------------------
                
                StreamWriter sw = new StreamWriter(@"resources\maps\" + obl + "_t.ini", false, Encoding.GetEncoding("Windows-1251"));
                for (i = 0; i < read_tree.Length; i++)
                {
                    if (read_tree[i] == "[Анализаторы]")
                        type1 = 0;
                    if (read_tree[i] == "[Измерители]")
                        type1 = 1;
                    //  read_tree[i].Substring(rtps.Length, 1) == "="
                    try
                    {
                        //------------------Если проблемы с сохранением списка устройств, смотреть сюда
                        //if ((read_tree[i].Substring(0, rtps.Length) != rtps) || (dev1 != dev) || (read_tree[i].Substring(rtps.Length, 1) != "="))
                        if ((read_tree[i].Substring(0, rtps.Length) != rtps) || (type1 != type) || (read_tree[i].Substring(rtps.Length, 1) != "="))
                            sw.WriteLine(read_tree[i]);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        if (read_tree[i] != "")
                            sw.WriteLine(read_tree[i]);
                    }
                }
                sw.Close();
                //}
            }
            d(false, device);
            this.Close();
            //Дальше в 7 форме обрабатывается закрытие этой формы.
        }

        private void button3_Click(object sender, EventArgs e)
        {
            device.del = true;
            device.mod = false;
            DialogResult res;
            res = System.Windows.Forms.MessageBox.Show("Вы действительно хотите удалить объект " + device.name + "?", "", MessageBoxButtons.OKCancel);
            if (res == DialogResult.Cancel)
                return;
            int type = del_device.type;
            int type1 = -1;
            int i = 0;
            string obl = "";
            string[] read_tree;
            string rtps = "";
            //bool dev = false;           //true  - измерители, false - анализаторы
            //dev = del_device.dev;
            rtps = device.name;            
            obl = device.obl;            
            read_tree = File.ReadAllLines(@"resources\maps\" + obl + ".ini", Encoding.GetEncoding("Windows-1251"));
            
            //-----------------------------------Удаление Объекта---------------------------------------------------
               
            //Возможно нужно использовать _t
            StreamWriter sw = new StreamWriter(@"resources\maps\" + obl + ".ini", false, Encoding.GetEncoding("Windows-1251"));
            for (i = 0; i < read_tree.Length; i++)
            {
                if (read_tree[i] == "[Анализаторы]")
                    type1 = 0;
                if (read_tree[i] == "[Измерители]")
                    type1 = 1;
                try
                {
                    //------------------Если проблемы с сохранением списка устройств, смотреть сюда
                    if ((read_tree[i].Substring(0, rtps.Length) != rtps) || (type1 != type) || (read_tree[i].Substring(rtps.Length, 1) != "="))
                        sw.WriteLine(read_tree[i]);
                }
                catch(ArgumentOutOfRangeException)
                {
                    if(read_tree[i] != "")
                        sw.WriteLine(read_tree[i]);
                }
            }
            sw.Close();
            d(false, device);
            this.Close();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            IPAddress ip;
            string name = textBox1.Text;
            if (!IPAddress.TryParse(textBox2.Text, out ip))
            {                
                MessageBox.Show("Введен некорректный IP-адрес");
                return;
            }
            if (!f9)
            {
                f9 = true;
                Form9 form9 = new Form9(new form9enable(func9), ip, name);
                form9.Owner = this;
                this.Enabled = false;
                form9.Show();
            }
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            string type = (string)((ComboBox)sender).SelectedItem;
            if (type == "Измерители")
            {
                checkBox1.Enabled = true;
                checkBox1.Show();
                label6.Show();
                button4.Show();
            }
            else
            {
                checkBox1.Enabled = false;
                checkBox1.Hide();
                label6.Hide();
                button4.Hide();
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            button4.Enabled = !checkBox1.Checked;
        }

        
    }
}
